﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DingApi.Models;
using System.Data;

using System.Web;
using System.IO;
using System.Text;
using Dingding.Helper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NCommon;


namespace DingApi.Controllers
{
    [RoutePrefix("api/UpDownFile")]
    public class UpDownFileController : ApiController
    {



        [HttpPost]
        [Route("PostUpFile")]

        //上传图片
        public HttpResponseMessage PostUpFile()
        {
            string msg = "";


            string formData_bill_type = HttpContext.Current.Request.Form["BILL_TYPE"];
            //SR22400194
            string formData_bill_no = HttpContext.Current.Request.Form["BILL_NO"];
            string formData_name_sub = HttpContext.Current.Request.Form["NAME_SUB"];

            var mapPath = "";

            if (formData_bill_type == "PASI")
            {
                mapPath = "D:\\pic\\_pic_new\\pasi\\" + formData_bill_no.Substring(2, 3) + "\\" + formData_bill_no + "\\";
            }
            else if (formData_bill_type == "PAEF")
            {
                mapPath = "D:\\pic\\_PA\\" +      formData_bill_no + "\\";
            }

            //质量在线封锁图片
            else if (formData_bill_type == "DCXA")
            {
                mapPath = "D:\\pic\\DCXA\\" + formData_bill_no.Substring(0, 6) + "\\" + formData_bill_no + "\\";
            }
            


            //虽然支持多记录，但前台钉钉只能传人1条记录；
            int count = HttpContext.Current.Request.Files.Count;

            for (int i = 0; i < count; i++)
            {
                try
                {
                    HttpPostedFile file = HttpContext.Current.Request.Files[i];
                    var fileExt = Path.GetExtension(file.FileName);
                    var fileName = formData_name_sub + "_" + DateTime.Now.ToString("ddHHmmssfff") + "_" + Guid.NewGuid().ToString("n").Substring(0, 5);

                    var mapPathFullPath = mapPath + fileName + fileExt; //硬盘物理路径
                    if (!Directory.Exists(mapPath))
                    {
                        Directory.CreateDirectory(mapPath);
                    }
                    file.SaveAs(mapPathFullPath);

                }
                catch (Exception ex)
                {
                    msg = ex.ToString();
                }
            }
            
            HttpResponseMessage result = new HttpResponseMessage
            {
                Content = new StringContent(msg, Encoding.GetEncoding("UTF-8"), "application/json")
            };
            return result;
        }


        ////
        ////
        ///// <summary>
        ///// 浏览图片2
        ///// add by 2022-09-28 该方法等PostGetFiles = PostViewFiles  + PostGetFilesNum
        ///// 原方法，考虑尚有其他程序待使用，故不注销，以后多推荐程序使用PostViewFiles2
        /////  
        ///// </summary>
        ///// <param name="obj"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("PostGetFiles")]
        //public System.Data.DataSet PostGetFiles([FromBody]  JObject obj)
        //{

        //    string BILL_TYPE    = obj["BILL_TYPE"] == null ? " " : obj["BILL_TYPE"].ToString();
        //    string BILL_NO      = obj["BILL_NO"] == null ? " " : obj["BILL_NO"].ToString();
        //    string NAME_SUB     = obj["NAME_SUB"] == null ? " " : obj["NAME_SUB"].ToString();


        //    var mapPath = "";
        //    var mapHttp = "";


        //    if (BILL_TYPE == "PASI") //收货图片
        //    {
        //        mapPath = "D:\\pic\\_pic_new\\pasi\\" + BILL_NO.Substring(2, 3) + "\\" + BILL_NO + "\\";
        //        mapHttp = "http://58.210.172.37:8019/_pic_new/pasi/" + BILL_NO.Substring(2, 3) + "/" + BILL_NO + "/";
        //    }
        //    else if (BILL_TYPE == "PAEF")  //二级库特殊物料资材编码图片
        //    {
        //        mapPath = "D:\\pic\\_PA\\" + BILL_NO + "\\";
        //        mapHttp = "http://58.210.172.37:8019/_PA/" + BILL_NO + "/";
        //    }


            
           
        //    EI.EIInfo outBlock = new EI.EIInfo();
        //    outBlock.Tables[0].TableName = "FILES";

        //    outBlock.Tables["FILES"].Columns.Add("FURL");
        //    outBlock.Tables["FILES"].Columns.Add("FNAME");
        //    outBlock.Tables["FILES"].Columns.Add("FTYPE");

           

        //    int files_num = 0; //文件数量
        //    //获取目录parentDir下的所有的文件，并过滤得到所有的文本文件
        //    if (Directory.Exists(mapPath))
        //    {
        //        string[] file = Directory.GetFiles(mapPath, NAME_SUB + "*");
        //        files_num = file.Length;

        //        string file_name = "";
        //        for (int i = 0; i < file.Length; i++)
        //        {
        //            file_name = Path.GetFileName(file[i].ToString());
        //            outBlock.Tables["FILES"].Rows.Add(mapHttp + file_name
        //                         , file_name
        //                         , Path.GetExtension(file_name));
        //        }
        //    }

            
        //    outBlock.Tables.Add("FILE_NUM");
        //    outBlock.Tables["FILE_NUM"].Columns.Add("NUM");
        //    outBlock.Tables["FILE_NUM"].Rows.Add(files_num);
             

        //    //系统信息；
        //    outBlock.Tables.Add("SYS");
        //    outBlock.Tables["SYS"].Columns.Add("FLAG");
        //    outBlock.Tables["SYS"].Columns.Add("MSG");
        //    outBlock.Tables["SYS"].Rows.Add(outBlock.sys_info.flag, outBlock.sys_info.msg);
        //    return outBlock;

        //}


        //浏览图片
        [HttpPost]
        [Route("PostViewFiles")]
        public System.Data.DataSet PostViewFiles([FromBody]  JObject obj)
        {

            string BILL_TYPE = obj["BILL_TYPE"] == null ? " " : obj["BILL_TYPE"].ToString();
            string BILL_NO = obj["BILL_NO"] == null ? " " : obj["BILL_NO"].ToString();
            string NAME_SUB = obj["NAME_SUB"] == null ? " " : obj["NAME_SUB"].ToString();


            var mapPath = "";
            var mapHttp = "";


            if (BILL_TYPE == "PASI") //收货图片
            {
                mapPath = "D:\\pic\\_pic_new\\pasi\\" + BILL_NO.Substring(2, 3) + "\\" + BILL_NO + "\\";
                mapHttp = "http://58.210.172.34:8050/pics/_pic_new/pasi/" + BILL_NO.Substring(2, 3) + "/" + BILL_NO + "/";
            }
            else if (BILL_TYPE == "PAEF")  //二级库特殊物料资材编码图片
            {
                mapPath = "D:\\pic\\_PA\\" + BILL_NO + "\\";
                mapHttp = "http://58.210.172.34:8050/pics/_PA/" + BILL_NO + "/";
            }
            if (BILL_TYPE == "DCXA") //现场质检图片
            {
                mapPath = "D:\\pic\\DCXA\\" + BILL_NO.Substring(0, 6) + "\\" + BILL_NO + "\\";
                mapHttp = "http://58.210.172.34:8050/pics/DCXA/" + BILL_NO.Substring(0, 6) + "/" + BILL_NO + "/";
            }

          



            EI.EIInfo outBlock = new EI.EIInfo();
            outBlock.Tables[0].TableName = "FILES";

            outBlock.Tables["FILES"].Columns.Add("FURL");
            outBlock.Tables["FILES"].Columns.Add("FNAME");
            outBlock.Tables["FILES"].Columns.Add("FTYPE");


            //获取目录parentDir下的所有的文件，并过滤得到所有的文本文件

            if (Directory.Exists(mapPath))
            {
                string[] file = Directory.GetFiles(mapPath, NAME_SUB + "*");

                string file_name = "";
                for (int i = 0; i < file.Length; i++)
                {
                    file_name = Path.GetFileName(file[i].ToString());
                    outBlock.Tables["FILES"].Rows.Add(mapHttp + file_name
                                 , file_name
                                 , Path.GetExtension(file_name));
                }
            }

            //系统信息；
            outBlock.Tables.Add("SYS");
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");
            outBlock.Tables["SYS"].Rows.Add(outBlock.sys_info.flag, outBlock.sys_info.msg);
            return outBlock;

        }  
        
         //获取单据下的图片数量
        [HttpPost]
        [Route("PostGetFilesNum")]
        public System.Data.DataSet PostGetFilesNum([FromBody]  JObject obj)
        {

            string BILL_TYPE    = obj["BILL_TYPE"] == null ? " " : obj["BILL_TYPE"].ToString();
            string BILL_NO      = obj["BILL_NO"] == null ? " " : obj["BILL_NO"].ToString();
            string NAME_SUB     = obj["NAME_SUB"] == null ? " " : obj["NAME_SUB"].ToString();


            var mapPath = "";
            if (BILL_TYPE == "PASI") //收货图片
            {
                mapPath = "D:\\pic\\_pic_new\\pasi\\" + BILL_NO.Substring(2, 3) + "\\" + BILL_NO + "\\";
            }
            else if (BILL_TYPE == "PAEF")  //二级库特殊物料资材编码图片
            {
                mapPath = "D:\\pic\\_PA\\" + BILL_NO + "\\";
            }


            int files_num = 0;
            if (Directory.Exists(mapPath))
            {
                string[] file = Directory.GetFiles(mapPath, NAME_SUB + "*");
                files_num = file.Length;
            }

            
           
            EI.EIInfo outBlock = new EI.EIInfo();
            outBlock.Tables[0].TableName = "FILES";
            outBlock.Tables["FILES"].Columns.Add("NUM");
            outBlock.Tables["FILES"].Rows.Add(files_num);
             



            //系统信息；
            outBlock.Tables.Add("SYS");
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");
            outBlock.Tables["SYS"].Rows.Add(outBlock.sys_info.flag, outBlock.sys_info.msg);
            return outBlock;

        }  







        [HttpPost]
        [Route("PostUpFile_inq")]

        //多记录查询
        public System.Data.DataSet PostUpFile_inq([FromBody]  JObject obj)
        {

          

            //obj对象区分大小写的； obj["ASMAT_NAME"] 报错。
            EI.EIInfo inBlock = new EI.EIInfo();

           

            inBlock.Tables[0].Columns.Add("COMPANY_CODE");
            inBlock.Tables[0].Columns.Add("PURCHASE_APPLY_BILL_NO");
            inBlock.Tables[0].Columns.Add("BRANCH_CODE");
            inBlock.Tables[0].Columns.Add("BILL_STATUS");

            inBlock.Tables[0].Columns.Add("REC_CREATOR");
            inBlock.Tables[0].Columns.Add("REC_CREATE_TIME");
            inBlock.Tables[0].Columns.Add("REC_REVISE_TIME");





            inBlock.Tables[0].Rows.Add();

            inBlock.sys_info.company_code = "LT";
            inBlock.sys_info.userid     = obj["USERID"].ToString();
            inBlock.sys_info.username = obj["USERNAME"].ToString();

            inBlock.sys_info.formname   = obj["FORMNAME"].ToString();


            inBlock.Tables[0].Rows[0]["COMPANY_CODE"] = obj["COMPANY_CODE"].ToString();
            inBlock.Tables[0].Rows[0]["PURCHASE_APPLY_BILL_NO"] = obj["PURCHASE_APPLY_BILL_NO"].ToString();
            inBlock.Tables[0].Rows[0]["BRANCH_CODE"] = obj["BRANCH_CODE"].ToString();
            inBlock.Tables[0].Rows[0]["BILL_STATUS"] = obj["BILL_STATUS"].ToString();
            inBlock.Tables[0].Rows[0]["REC_CREATOR"] = obj["REC_CREATOR"].ToString();

            inBlock.Tables[0].Rows[0]["REC_CREATE_TIME"] = obj["REC_CREATE_TIME"].ToString();
            inBlock.Tables[0].Rows[0]["REC_REVISE_TIME"] = obj["REC_REVISE_TIME"].ToString();


            //仅查询最近最近2天的；不然数据太多，影响小程序效率；
            if (inBlock.Tables[0].Rows[0]["REC_CREATE_TIME"].ToString().Trim() == "")
            {
                inBlock.Tables[0].Rows[0]["REC_CREATE_TIME"] = DateTime.Now.AddMonths(-1).ToString("yyyyMMddHHmmss");
            }

            if (inBlock.Tables[0].Rows[0]["REC_REVISE_TIME"].ToString().Trim() == "")
            {
                inBlock.Tables[0].Rows[0]["REC_REVISE_TIME"] = DateTime.Now.AddDays(1).ToString("yyyyMMddHHmmss");
            }

          



            EI.EIInfo outBlock = EI.EITuxedo.CallService("UpFile_inq", inBlock);

            //小代码转换；
            EI.EIInfo outBlock_TEMP = EF.Utility.GetCodeClassValue("PA29", "PAA1", "PA30", "FIBR", "FIDP");
            DataTable dtTemp = null;

            EI.EIInfo outBlock_TEMP2 = EF.Utility.ExecQuery("select t.STOCK_NO CODE ,t.stock_name as CODE_DESC_1_CONTENT from tsimm01 t");
           
        

            for (int i = outBlock.Tables[0].Rows.Count - 1; i >= 0; i--)
            {

                if (outBlock.Tables[0].Rows[i]["REMARK"].ToString() == "对外销售出库时自动生成")
                {
                    outBlock.Tables[0].Rows[i].Delete();
                    continue;
                }

                string APN = outBlock.Tables[0].Rows[i]["APN"].ToString();
                if (APN.Trim() != "")
                {
                    dtTemp = outBlock_TEMP.Tables["PAA1"].Select("CODE  = '" + APN + "'").CopyToDataTable<DataRow>();
                    outBlock.Tables[0].Rows[i]["APN"] = dtTemp.Rows[0]["CODE_DESC_1_CONTENT"];
                }

                string APPLY_CLASSIFY = outBlock.Tables[0].Rows[i]["APPLY_CLASSIFY"].ToString();
                if (APPLY_CLASSIFY.Trim() != "")
                {
                    dtTemp = outBlock_TEMP.Tables["PA29"].Select("CODE  = '" + APPLY_CLASSIFY + "'").CopyToDataTable<DataRow>();
                    outBlock.Tables[0].Rows[i]["APPLY_CLASSIFY"] = dtTemp.Rows[0]["CODE_DESC_1_CONTENT"];
                }

                string STOCK_NO = outBlock.Tables[0].Rows[i]["STOCK_NO"].ToString();
                if (STOCK_NO.Trim() != "")
                {
                    dtTemp = outBlock_TEMP2.Tables[0].Select("CODE  = '" + STOCK_NO + "'").CopyToDataTable<DataRow>();
                    outBlock.Tables[0].Rows[i]["STOCK_NO"] = dtTemp.Rows[0]["CODE_DESC_1_CONTENT"];
                }


              

                string BILL_STATUS = outBlock.Tables[0].Rows[i]["BILL_STATUS"].ToString();
                if (BILL_STATUS.Trim() != "")
                    dtTemp = outBlock_TEMP.Tables["PA30"].Select("CODE  = '" + BILL_STATUS + "'").CopyToDataTable<DataRow>();

                if (dtTemp != null && dtTemp.Rows.Count == 1)
                    outBlock.Tables[0].Rows[i]["BILL_STATUS"] = dtTemp.Rows[0]["CODE_DESC_1_CONTENT"];

                string branch_code = outBlock.Tables[0].Rows[i]["BRANCH_CODE"].ToString();
                if (branch_code.Trim() != "")
                    dtTemp = outBlock_TEMP.Tables["FIBR"].Select("CODE  = '" + branch_code + "'").CopyToDataTable<DataRow>();

                if (dtTemp != null && dtTemp.Rows.Count == 1)
                    outBlock.Tables[0].Rows[i]["BRANCH_CODE"] = dtTemp.Rows[0]["CODE_DESC_1_CONTENT"];


                string dptment_code = outBlock.Tables[0].Rows[i]["DPTMENT_CODE"].ToString();
                if (dptment_code.Trim() != "")
                    dtTemp = outBlock_TEMP.Tables["FIDP"].Select("CODE  = '" + dptment_code + "'").CopyToDataTable<DataRow>();

                if (dtTemp != null && dtTemp.Rows.Count == 1)
                    outBlock.Tables[0].Rows[i]["DPTMENT_CODE"] = dtTemp.Rows[0]["CODE_DESC_1_CONTENT"];

                string apply_date = outBlock.Tables[0].Rows[i]["APPLY_DATE"].ToString();
                if (apply_date.Length>=8)
                outBlock.Tables[0].Rows[i]["APPLY_DATE"] = apply_date.Substring(0, 4) + "-" + apply_date.Substring(4, 2) + "-" + apply_date.Substring(6, 2);



                string DELIVY_EXPECTED_DATE = outBlock.Tables[0].Rows[i]["DELIVY_EXPECTED_DATE"].ToString();
                if (DELIVY_EXPECTED_DATE.Length >= 8)
                    outBlock.Tables[0].Rows[i]["DELIVY_EXPECTED_DATE"] = DELIVY_EXPECTED_DATE.Substring(0, 4) + "-" + DELIVY_EXPECTED_DATE.Substring(4, 2) + "-" + DELIVY_EXPECTED_DATE.Substring(6, 2);


                



            }

            
            
            outBlock.Tables[0].TableName = "Table0";


            //系统信息；
            outBlock.Tables.Add("SYS");
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");
            outBlock.Tables["SYS"].Rows.Add(outBlock.sys_info.flag, outBlock.sys_info.msg);            
            return outBlock;


        }


        #region 可以使用，从微信小程序启发而来，web文件上传；
        [HttpPost]
        [Route("PostUpFile_Info")]       
        public string   PostUpFile_Info()
        { 
            string msg = "";
            try
            {
                HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                if (files.Count > 0)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile file = HttpContext.Current.Request.Files[0];
                        var path = "/upload/";
                        var mapPath = HttpContext.Current.Server.MapPath(path); //硬盘物理目录
                        var fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        var fileExt = Path.GetExtension(file.FileName);
                        var mapPathFullPath = mapPath + fileName + fileExt; //硬盘物理路径
                        var siteFullPath = path + fileName + fileExt; //网站路径
                        if (!Directory.Exists(mapPath))
                        {
                            Directory.CreateDirectory(mapPath);
                        }
                        file.SaveAs(mapPathFullPath);
                        msg = siteFullPath.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message; 
            } 

            return "hell" + msg;


        }
        #endregion


        //[HttpPost]
        //[Route("PostDownFiles")]
        //public System.Data.DataSet PostDownFiles([FromBody]  JObject obj)
        //{

        //    string parentDir = "/upload/";
        //    EI.EIInfo outBlock = new EI.EIInfo();
        //    outBlock.Tables[0].TableName = "FILES";

        //    outBlock.Tables["FILES"].Columns.Add("FURL");
        //    outBlock.Tables["FILES"].Columns.Add("FNAME");
        //    outBlock.Tables["FILES"].Columns.Add("FTYPE");

        //    var mapPath = HttpContext.Current.Server.MapPath(parentDir); //硬盘物理目录
        //    mapPath = "D:\\ERP_APP\\fabu\\Web8088\\WebDevice_ZB\\upload\\";

            
        //    //获取目录parentDir下的所有的文件，并过滤得到所有的文本文件
        //    string[] file = Directory.GetFiles(mapPath, ".jpg");
        //    file = Directory.GetFiles(mapPath);
        //    file = Directory.GetFiles(mapPath, "*884*");

        //    for (int i = 0; i < file.Length; i++)
        //    {
        //        outBlock.Tables["FILES"].Rows.Add("http://58.210.172.37:8019/_SQ/" + "/" + file[i].ToString()
        //                     , file[i]
        //                     , "jpg");
                
        //    }

        //    //系统信息；
        //    outBlock.Tables.Add("SYS");
        //    outBlock.Tables["SYS"].Columns.Add("FLAG");
        //    outBlock.Tables["SYS"].Columns.Add("MSG");
        //    outBlock.Tables["SYS"].Rows.Add(outBlock.sys_info.flag, outBlock.sys_info.msg);
        //    return outBlock;

        //}  

        #region 可 ；
        [HttpPost]
        [Route("PostUpFileFtp_Info")]
        public string PostUpFile_Info2()
        {
            string msg = "";
            try
            {
                HttpPostedFile file = HttpContext.Current.Request.Files[0];

                var path = "/upload/";
                var mapPath = HttpContext.Current.Server.MapPath(path); //硬盘物理目录
                var fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                var fileExt = Path.GetExtension(file.FileName);
                var mapPathFullPath = mapPath + fileName + fileExt; //硬盘物理路径
                var siteFullPath = path + fileName + fileExt; //网站路径
                if (!Directory.Exists(mapPath))
                {
                    Directory.CreateDirectory(mapPath);
                }
                file.SaveAs(mapPathFullPath);
                msg = siteFullPath.ToString();

                //D:\ERP_APP\fabu\Web8088\WebDevice_ZB\upload
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }


            return "hell" + msg;


        }
        #endregion





        #region 参考程序：微信小程序图片上传【无法使用，有参考价值】
        [HttpPost]
        [Route("PostUpFile_Info2")]
        public HttpResponseMessage WxPostFile()
        {  
            ////定义
            //ResponseResult obj = new ResponseResult();
            //try
            //{
            //    HttpPostedFile file = HttpContext.Current.Request.Files[0];
            //    var userId = HttpContext.Current.Request["userId"];
            //    var path = "/upload/";
            //    var mapPath = HttpContext.Current.Server.MapPath(path); //硬盘物理目录
            //    var fileName = Until.GetNowTimeString();
            //    var fileExt = Path.GetExtension(file.FileName);
            //    var mapPathFullPath = mapPath + fileName + fileExt; //硬盘物理路径
            //    var siteFullPath = path + fileName + fileExt; //网站路径
            //    if (!Directory.Exists(mapPath))
            //    {
            //        Directory.CreateDirectory(mapPath);
            //    }
            //    file.SaveAs(mapPathFullPath);
            //    obj.status = true;
            //    obj.message = siteFullPath;
            //    obj.info = userId;
            //}
            //catch (Exception ex)
            //{
            //    obj.status = false;
            //    obj.message = ex.Message;
            //}
            //var resultObj = JsonConvert.SerializeObject(obj);
            HttpResponseMessage result = new HttpResponseMessage
            {
                // Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json")
            };
            return result;
        }
        #endregion 
    }
}